package com.example.bankseckill.controller;

import com.example.bankseckill.Validator.Role;
import com.example.bankseckill.pojo.Product;
import com.example.bankseckill.pojo.SeckillOrder;
import com.example.bankseckill.pojo.SeckillProduct;
import com.example.bankseckill.pojo.User;
import com.example.bankseckill.pojo.vo.*;
import com.example.bankseckill.service.IProductService;
import com.example.bankseckill.service.ISeckillOrderService;
import com.example.bankseckill.service.ISeckillProductService;
import com.example.bankseckill.service.IUserService;
import com.example.bankseckill.utils.FastDFSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: liyangjing
 * @Date: 2022/02/10/10:58
 * @Description:
 *
 *  管理员接口
 *
 */
@Api(tags = "管理员接口")
@RestController
@RequestMapping("/bank/admin")
public class adminController {
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private IUserService userService;

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private IProductService productService;

    @Autowired
    private ISeckillProductService seckillProductService;

    /**
     * login 登录接口
     * @param user
     * @param request
     * @return
     */
    @ApiOperation("管理员登录接口")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public RespBean AdminLogin(@RequestBody LoginUser user, HttpServletRequest request){
        return  userService.adminlogin(user,request);
    }

    /**
     * 管理员查看所有秒杀订单(分页)
     * @param currentPage
     * @param size
     * @param keywords
     * @return
     */
    @ApiOperation(value = "查看所有秒杀订单(分页)")
    @RequestMapping(value = "/getsecorders",method =RequestMethod.POST)
    @Role(value = 1)
    public RespPageBean getSecOrders(@RequestParam(defaultValue = "1")Integer currentPage,
                                     @RequestParam(defaultValue = "10")Integer size,
                                     String keywords){
        return seckillOrderService.getSecKillOrderByPage(currentPage,size,keywords);
    }
// =================================================用户功能===================================================================
    /**
     * 管理员查看所有用户（分页）
     * @param currentPage
     * @param size
     * @param username
     * @param phone
     * @param identitycard
     * @return
     */
    @ApiOperation(value = "查看所有用户(分页)")
    @RequestMapping(value = "/user/getAllInfo",method = RequestMethod.POST)
    @Role(value = 1)
    public RespPageBean getAllUserInfo(@RequestParam(defaultValue = "1")Integer currentPage,
                                   @RequestParam(defaultValue = "10")Integer size,
                                       String username,
                                       String phone,
                                       String identitycard){
        return userService.getAllUserInfo(currentPage,size,username,phone,identitycard);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @ApiOperation(value = "单个删除用户")
    @RequestMapping(value = "/user/delete/{id}",method = RequestMethod.DELETE)
    @Role(value = 1)
    public RespBean deleteUser(@PathVariable Integer id){
        boolean result = userService.removeById(id);
        if(!result){
            return RespBean.error("删除失败！");
        }
        return RespBean.success("删除用户成功","删除成功！");
    }

    /**
     * 批量删除用户
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量删除用户")
    @DeleteMapping("/user/delete")
    @Role(value = 1)
    public RespBean deleteUserByIds(Integer[] ids){
        if (userService.removeByIds(Arrays.asList(ids))) {
            return RespBean.success("批量删除用户成功 ","批量删除成功！");
        }
        return RespBean.error("批量删除失败！");
    }

    /**
     * 管理员更改用户状态
     * @param userId
     * @return
     */
    @ApiOperation(value = "更新用户启用状态")
    @PutMapping("/user/update")
    @Role(value = 1)
    public RespBean updateUserStatus(int userId,int enable){
        User user = userService.getById(userId);
        if(user==null){
            return RespBean.error("没有此用户!");
        }
        user.setEnable(enable);
        if(enable>1){
            user.setEnable(1);
        }
        //更新用户状态
        userService.updateById(user);
        return RespBean.success("更新用户状态成功!",null);
    }

    /**
     * 更改用户所有状态
     * @param userId
     * @param enable
     * @param riskLevel
     * @param ishonest
     * @param isinwork
     * @return
     */
    @ApiOperation("更改用户所有状态（风险、工作、失信、启用）")
    @PutMapping("/user/StatusUpdate")
    @Role(value = 1)
    public RespBean updateUserStatuss(int userId,int enable,int riskLevel,int ishonest,int isinwork){
        User user = userService.getById(userId);
        if(user==null){
            return RespBean.error("没有此用户!");
        }
        if (enable == 1 || enable == 0) {
            //启用状态
            user.setEnable(enable);
        }else {
            return RespBean.error("启用状态输入错误!");
        }
        //风险等级
        if (riskLevel == 1 || riskLevel == 0||riskLevel==2) {
            user.setRiskLevel(riskLevel);
        }else {
            return RespBean.error("风险状态输入错误!");
        }
        //失信
        if (ishonest == 1 || ishonest == 0) {
            user.setIshonest(ishonest);
        }else {
            return RespBean.error("失信状态输入错误!");
        }
        //是否工作
        if (isinwork == 1 || isinwork == 0) {
            user.setIsinwork(isinwork);
        }else {
            return RespBean.error("工作状态输入错误!");
        }
        //更新用户状态
        userService.updateById(user);
        return RespBean.success("更新用户状态成功!",null);
    }
//    ============================================产品功能===========================================================
    /**
     * 更换产品图片
     * @param productId
     * @param file
     * @return
     */
    @ApiOperation(value = "更换产品图片")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "头像", dataType = "MultipartFile")})
    @RequestMapping(value = "/product/picture",method = RequestMethod.POST)
    @Role(value = 1)
    public RespBean updateUserAvatar(Integer productId, MultipartFile file){
        if(file==null){
            return RespBean.error(RespBeanEnum.FILE_EMPTY);
        }
        Product product = productService.getById(productId);
        if(product==null)
        {
            return RespBean.error("未找到该产品");
        }
        //获取上传文件地址（利用fastdfutil）
        String[] fileabsolutePath = FastDFSUtils.upload(file);
        String url = FastDFSUtils.getTrackerUrl()+fileabsolutePath[0]+"/"+fileabsolutePath[1];
        return productService.updateProductPicture(product,url);
    }

    /**
     * 单个删除产品
     * @param ProductId
     * @return
     */
    @ApiOperation(value = "单个删除产品")
    @RequestMapping(value = "/product/delete/{ProductId}",method = RequestMethod.DELETE)
    @Role(value = 1)
    public RespBean deleteProductById(@PathVariable Integer ProductId){
        boolean result = productService.removeById(ProductId);
        if(result){
            return RespBean.success("删除产品成功！");
        }
        return RespBean.error("删除产品失败！");
    }

    /**
     * 批量删除产品
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量删除产品")
    @RequestMapping(value = "/product/delete",method = RequestMethod.DELETE)
    @Role(value = 1)
    public RespBean deleteProductByIds(Integer[] ids){
        if(productService.removeByIds(Arrays.asList(ids))){
            return RespBean.success("批量删除成功！");
        }else {
            return RespBean.error("批量删除失败！");
        }
    }

    /**
     * 新增产品 不需要id
     * @param product
     * @return
     */
    @ApiOperation(value = "新增产品")
    @RequestMapping(value = "/product/add",method = RequestMethod.POST)
    @Role(value = 1)
    public RespBean addProduct(@RequestBody @Valid Product product){
        //产品时间精确到 秒 2022-02-10 00:00:00
        //插入默认图片
        product.setPicture("http://81.70.146.198:888/group1/M00/00/00/UUaSxmIKgymARZmlAAAM6L95WeM857.png");
        boolean result = productService.save(product);
        if(result){
            return RespBean.success("增加产品成功！");
        }
        return RespBean.error("增加产品失败！");
    }

    /**
     * 更新产品
     * @param product
     * @return
     */
    @ApiOperation(value = "更新产品&&更新缓存产品风险等级")
    @RequestMapping(value = "/product/update",method = RequestMethod.PUT)
    @Role(value = 1)
    public RespBean updateproduct(@RequestBody @Valid Product product){
        boolean result = productService.updateById(product);
        redisTemplate.opsForValue().set("RiskLevel:"+product.getId(),product.getRiskLevel());
        if(result){
            return RespBean.success("更新产品成功！");
        }
        return RespBean.error("更新产品失败！");
    }
    //==========================================seckillproduct============================================
    /**
     * 只需要上传 productId就行
     * @param seckillProduct
     * @return
     */
    @ApiOperation(value = "创建新的秒杀产品")
    @RequestMapping(value = "/seckillproduct/config",method = RequestMethod.POST)
    @Role(value = 1)
    public RespBean configSeckillProduct(@RequestBody @Valid SeckillProduct seckillProduct){
        //查询原价产品是否存在
        Product product = productService.getById(seckillProduct.getProductId());
        if(product==null){
            return RespBean.error("没有此种原产品,配置失败！");
        }
        boolean result = seckillProductService.save(seckillProduct);
        if(result){
            return RespBean.success("配置秒杀活动成功！");
        }
        return RespBean.error("配置秒杀活动失败！");
    }

    /**
     * 删除某个秒杀活动
     * @param seckillProductId
     * @return
     */
    @ApiOperation(value = "删除某个秒杀产品")
    @RequestMapping(value = "/seckillproduct/delete/{seckillProductId}",method = RequestMethod.DELETE)
    @Role(value = 1)
    public RespBean deleteseckillProductById(@PathVariable Integer seckillProductId){
        boolean result = seckillProductService.removeById(seckillProductId);
        if(result){
            return RespBean.success("删除成功！");
        }
        return RespBean.error("删除失败！");
    }

    /**
     * 更新某个秒杀活动
     * @param seckillProduct
     * @return
     */
    @ApiOperation(value = "更新某个秒杀产品")
    @RequestMapping(value = "/seckillproduct/update",method = RequestMethod.PUT)
    @Role(value = 1)
    public RespBean updateSeckillProductById(@RequestBody @Valid SeckillProduct seckillProduct){
        if(seckillProduct.getId()==null){
            return RespBean.error("没有该种秒杀产品,更新失败！");
        }
        //查询原价产品是否存在
        Product product = productService.getById(seckillProduct.getProductId());
        //如果不存在
        if(product==null){
            return RespBean.error("没有此种原产品,更新失败！");
        }
        boolean result = seckillProductService.updateById(seckillProduct);
        if(result){
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }

    @ApiOperation(value = "修改秒杀产品的状态")
    @RequestMapping(value = "/seckillproduct/status",method = RequestMethod.PUT)
    @Role(value = 1)
    public RespBean updateProductStatus(Integer seckillProduct,boolean status){
        SeckillProduct product = seckillProductService.getById(seckillProduct);
        if(product==null){
            return RespBean.error("秒杀产品为空,修改状态失败！");
        }
        //如果status为true 则开启活动
        if(status){
            product.setEnable(1);
            boolean result = seckillProductService.updateById(product);
            if(result){
                return RespBean.success("活动已开启！");
            }
            return RespBean.error("修改活动状态失败！");
        }
        else{
            product.setEnable(0);
            boolean result = seckillProductService.updateById(product);
            if(result){
                return RespBean.success("活动已禁用！");
            }
            return RespBean.error("修改活动状态失败！");
        }
    }
}
